import React from 'react'
import style from './index.module.scss'
import { Button, Form, Input } from 'antd'
import makeFriend from '@/assets/home/logo.png'
import { useNavigate } from 'react-router-dom'
import { login } from '@/common/api'
import { setLs } from '@/common/common'
import { connect } from 'react-redux'
function Login({addUser}) {
  const navigate = useNavigate()
  const onFinish = async (params) => {
    const RES = await login(params)
    if (RES.code === 200) {
      setLs(RES.data, 'userInfo')
      setLs(RES.data.privacyList,"privacyList")
      addUser(RES.data)
      navigate('/explor',{replace:true})
      // window.location.reload(); // 强制刷新页面
    }
  };
  // 校验账号
  const valiDatateUsername = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('请输入账号！'));
    }
    if (!value || !/^\d{11}$/.test(value)) {
      return Promise.reject(new Error('请输入11位数的账号！'));
    }
    return Promise.resolve();
  }
  // 校验密码
  const valiDatatePwd = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('请输入密码！'));
    }
    if (!value || !/^\d{6,12}$/.test(value)) {
      return Promise.reject(new Error('请输入6-12位数的密码！'));
    }
    return Promise.resolve();
  }
  return (
    <div className={style.login}>
      <div className={style.loginTop}>
        <div className={style.title}>
          <img src={makeFriend} alt="" /><p>趣纷享</p>
        </div>
        <Form
          name="basic"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"

            rules={[
              {
                validator: valiDatateUsername,
              },
            ]}
          >
            <Input placeholder='请输入账号' />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              { validator: valiDatatePwd }
            ]}
          >
            <Input.Password placeholder='请输入密码' />
          </Form.Item>
          <Form.Item
          >
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
          <p className={style.toRegister}>没有趣纷享账号？<span className={style.registerNow} onClick={() => navigate('/register')}>立即注册</span></p>
        </Form>
      </div>
      <div className={style.bgc}>
      </div>
    </div>
  )
}
export default connect(null, dispatch => {
  return {
    addUser: (params) => dispatch({type:"addUser",payload:params})
  }
})(Login)
